package com.choudou5.nlp.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.choudou5.nlp.consts.AnalysisConsts;
import com.choudou5.solr.util.JsonUtil;
import com.choudou5.solr.util.LogDeBugUtil;
import com.choudou5.solr.util.StrUtil;
import com.choudou5.solr.util.bean.WordBean;
import com.choudou5.solr.util.http.HttpUtils;

import java.util.*;

/**
 * @name 玻森
 * @author choudou5
 * @date 2018-08-08
 */
public class BosonUtil {

    public static void main(String[] args) {
        String appKey = "SYJq9Oen.26893.SwY0W94sUZwF";
        getTextAnalysis(appKey, "波尔多红酒怎么样");
    }

    /**
     * 文本分析
     * 免费账号 每天50w次，QPS限制22
     * http://docs.bosonnlp.com/tag.html
     */
    public static String getTextAnalysis(String appKey, String text) {
        Map<String, String> headers = new HashMap<>();
        headers.put("X-Token", appKey);
        String resp = HttpUtils.postJson(AnalysisConsts.BOSON_API, JsonUtil.toStr(text), headers, "UTF-8");
        LogDeBugUtil.debug(resp);
        return resp;
    }

    /**
     * 文本分析  http://docs.bosonnlp.com/tag.html
     * 免费接口
     */
    public static Set<WordBean> getTextAnalysis(String text) {
        Map<String, Object> params = new HashMap<>();
        params.put("data", text);
        String resp = HttpUtils.postSSL("https://bosonnlp.com/analysis/tag", params, "UTF-8");
//        LogDeBugUtil.debug(resp);
        if(StrUtil.isBlank(resp))
            return null;
        JSONArray array = JsonUtil.toJsonArray(resp);
        JSONObject json = array.getJSONObject(0);
        if(json.getJSONArray("word") != null) {
            JSONArray words = json.getJSONArray("word");
            JSONArray tags = json.getJSONArray("tag");
            Set<WordBean> list = new HashSet<>();
            for (int i = 0; i < words.size(); i++) {
                list.add(new WordBean(words.getString(i), tags.getString(i)));
            }
//            LogDeBugUtil.debug(list);
            return list;
        }
        return null;
    }

}
